package com.guinea.account.service;

import java.io.Serializable;
import java.util.Set;

import org.springframework.util.Assert;

import com.guinea.account.dao.ResourceDao;
import com.guinea.account.entity.Resource;
import com.guinea.account.entity.Role;
import com.guinea.core.acegi.cache.AcegiCacheManager;
import com.guinea.core.orm.hibernate.HibernateDao;
import com.guinea.core.service.CRUDManager;

/**
 * @author huaxiaz
 * @see HibernateEntityDao
 * @see org.springside.core.dao.HibernateGenericDao
 */
public class ResourceManager extends CRUDManager {
	private AcegiCacheManager acegiCacheManager;
	private ResourceDao resourceDao;

	public HibernateDao getEntityDao() {
		return getResourceDao();
	}

	public Resource getResource(Serializable id) {
		return (Resource)getResourceDao().get(id);
	}

	public ResourceDao getResourceDao() {
		return resourceDao;
	}

	public void setResourceDao(ResourceDao resourceDao) {
		this.resourceDao = resourceDao;
	}

	public void setAcegiCacheManager(AcegiCacheManager acegiCacheManager) {
		this.acegiCacheManager = acegiCacheManager;
	}
	
    public String[] getRelativeRoleIds(Serializable id) {
        Role role;
        Resource resource = (Resource)get(id);
        Set roles = resource.getRoles();
        String[] relativeRoleIds = new String[roles.size()];
        int i = 0;
        for (java.util.Iterator iter = roles.iterator(); iter.hasNext();) {
            role = (Role) iter.next();
            Assert.notNull(role.getId());
            relativeRoleIds[i] = String.valueOf(role.getId().longValue());
            i++;
        }
        return relativeRoleIds;
    }
	public void saveResource(Resource resource){
		Serializable id = resource.getId();
		String originString = null;
		if(id != null)
			originString = ((Resource)get(id)).getResourceString();
		getResourceDao().save(resource);
		if(originString == null)
			originString = resource.getResourceString();
		acegiCacheManager.modifyResourceInCache(resource,originString);
	}
	//标记删除
	public void eraseResource(Resource resource){
		getResourceDao().save(resource);
		String originResString = resource.getResourceString();
		if(originResString != null)
			acegiCacheManager.getResourceCache().removeAuthorityFromCache(originResString);
	}
	public void deleteResource(Resource resource){
		String originResString = null;
		if(resource != null)
			originResString = resource.getResourceString();
		getResourceDao().delete(resource);
		if(originResString != null)
			acegiCacheManager.getResourceCache().removeAuthorityFromCache(originResString);
	}

}
